﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataReceiver.DataAPI
{
    public class TickFilter
    {
        Queue<Model_Tick> queue_Tick = new Queue<Model_Tick>();
        Dictionary<string,Model_Tick> dic_Tick = new Dictionary<string,Model_Tick>();
        List<Model_Tick> bufferTicks = new List<Model_Tick>();
        System.Timers.Timer timer_1min;

        //初始化定时器
        public TickFilter()
        {
            timer_1min = new System.Timers.Timer(60*1000);
            timer_1min.Elapsed += new System.Timers.ElapsedEventHandler(onTimer_1min);
            timer_1min.AutoReset = true;
            timer_1min.Enabled = true;
        }
        public void onTimer_1min(object sender,System.Timers.ElapsedEventArgs args)
        {
            moveTicks();
        }

        //添加tick到列队和字典
        int tickCount = 0;
        object locker = new object();
        public void AddTick(Model_Tick tick)
        {
            //过滤条件
            if(Math.Abs((tick.UpdateTime - DateTime.Now).Minutes) > 1)
            {
                return;
            }

            //通过队列和字典检查重复（多连接接收）
            tickCount++;
            string key = tick.InstrumentID + '_' + tick.UpdateTime.Ticks.ToString();
            lock (locker)
            {
                if (!dic_Tick.ContainsKey(key))
                {
                    dic_Tick.Add(key, tick);
                    queue_Tick.Enqueue(tick);

                    if(tickCount > 4000 && queue_Tick.Count > 0)
                    {
                        //超过一定数量，每增减一条就要清除一条，保证字典不要太大
                        Model_Tick dqTick = queue_Tick.Dequeue();
                        string dqKey = dqTick.InstrumentID + '_' + dqTick.UpdateTime.Ticks.ToString();
                        dic_Tick.Remove(dqKey);

                        //加入到缓存
                        bufferTicks.Add(tick);
                    }
                }
            }
        }

        //搬运一批tick
        public delegate void OnTicksMoveEvent(List<Model_Tick> tick);
        public event OnTicksMoveEvent OnTicksMoveing;
        void moveTicks()
        {
            lock(locker)
            {
                if (OnTicksMoveing != null && bufferTicks.Count > 0)
                {
                    OnTicksMoveing(bufferTicks);
                    bufferTicks.Clear();
                }
            }

        }
    }
}
